// 在页面中定义激励视频广告
let videoAd = null
// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
import {
  searchOilPrice
} from '../../../api/http'
const util = require('../../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: ['广东省', '广州市', '海珠区'],
    customItem: '全部',
    // provinceData: {},
    arr: [],
    historys: [],
    date: "2025/05/30",
    week: "星期五",
    time: "17:14",
    isShow2: false,
    imgSrc: '/static/qrcode.jpg',
    copyText: '油价查询小程序链接: https://pan.baidu.com/s/1_YUGQQiw4yAo0CjzoEMveQ?pwd=jfb7 提取码: jfb7'
  },
  // 获取日期 星期 时间
  getCurrentDateTime() {
    let dt = new Date();
    let YY = dt.getFullYear();
    let MM = dt.getMonth() + 1;
    let DD = dt.getDate();
    MM = util.formatNumber(MM);
    DD = util.formatNumber(DD);
    let week = dt.getDay()
    let h = dt.getHours();
    let m = dt.getMinutes();
    let s = dt.getSeconds();
    h = util.formatNumber(h);
    m = util.formatNumber(m);
    s = util.formatNumber(s);
    this.setData({
      date: `${YY}/${MM}/${DD}/`,
      week: ['天', '一', '二', '三', '四', '五', '六'][week],
      time: `${h}:${m}:${s}`,
    })
  },
  // 编写方法处理历史存储
  historyDataFn() {
    let historys = wx.getStorageSync("YOUJIA_HISTORY")
    if (historys) {
      this.setData({
        historys: historys
      })
    }
  },
  // 选择省份 城市 地区
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
    // 查询数据
    this.searchOilPriceFn();
  },
  // 编写方法 获取后台数据
  async searchOilPriceFn() {
    let provice = this.data.region[0];
    // provice = provice.slice(0,2);
    provice = provice.replace('省', '')
    console.log({
      provice
    })
    wx.showLoading({
      title: '正在查询...',
    })
    await searchOilPrice({
        msg: provice
      })
      .then(
        content => {
          console.log("后台数据:", content)
          let arr = []
          if (provice == '黑龙江') {
            let arr1 = [];
            let arr2 = [];
            if (content.data.area[0]) {
              let provinceData = content.data.area[0].areaData
              arr1 = [{
                  text: "92",
                  name: "汽油(南区)",
                  price: provinceData.GAS_92,
                  price_status: provinceData.GAS_92_STATUS,
                  GAS_92: provinceData.GAS_92,
                  GAS_92_STATUS: provinceData.GAS_92_STATUS,
                },
                {
                  text: "95",
                  name: "汽油(南区)",
                  price: provinceData.GAS_95,
                  price_status: provinceData.GAS_95_STATUS,
                  GAS_95: provinceData.GAS_95,
                  GAS_95_STATUS: provinceData.GAS_95_STATUS,
                },
                {
                  text: "98",
                  name: "汽油(南区)",
                  price: provinceData.GAS_98,
                  price_status: provinceData.GAS_98_STATUS,
                  GAS_98: provinceData.GAS_98,
                  GAS_98_STATUS: provinceData.GAS_98_STATUS,
                },
                {
                  text: "0",
                  name: "柴油(南区)",
                  price: provinceData.CHECHAI_0,
                  price_status: provinceData.CHECHAI_0_STATUS,
                  CHECHAI_0: provinceData.CHECHAI_0,
                  CHECHAI_0_STATUS: provinceData.CHECHAI_0_STATUS,
                }
              ];
            }
            if (content.data.area[1]) {
              let provinceData = content.data.area[1].areaData
              arr2 = [{
                  text: "92",
                  name: "汽油(北区)",
                  price: provinceData.GAS_92,
                  price_status: provinceData.GAS_92_STATUS,
                  GAS_92: provinceData.GAS_92,
                  GAS_92_STATUS: provinceData.GAS_92_STATUS,
                },
                {
                  text: "95",
                  name: "汽油(北区)",
                  price: provinceData.GAS_95,
                  price_status: provinceData.GAS_95_STATUS,
                  GAS_95: provinceData.GAS_95,
                  GAS_95_STATUS: provinceData.GAS_95_STATUS,
                },
                {
                  text: "98",
                  name: "汽油(北区)",
                  price: provinceData.GAS_98,
                  price_status: provinceData.GAS_98_STATUS,
                  GAS_98: provinceData.GAS_98,
                  GAS_98_STATUS: provinceData.GAS_98_STATUS,
                },
                {
                  text: "0",
                  name: "柴油(北区)",
                  price: provinceData.CHECHAI_0,
                  price_status: provinceData.CHECHAI_0_STATUS,
                  CHECHAI_0: provinceData.CHECHAI_0,
                  CHECHAI_0_STATUS: provinceData.CHECHAI_0_STATUS,
                }
              ];
            }
            arr = [...arr1, ...arr2];
            console.log(arr);
            this.setData({
              arr: arr
            })
          } else {
            let provinceData = content.data.provinceData;
            // 整合数据完毕
            arr = [{
                text: "92",
                name: "汽油",
                price: provinceData.GAS_92,
                price_status: provinceData.GAS_92_STATUS,
                GAS_92: provinceData.GAS_92,
                GAS_92_STATUS: provinceData.GAS_92_STATUS,
              },
              {
                text: "95",
                name: "汽油",
                price: provinceData.GAS_95,
                price_status: provinceData.GAS_95_STATUS,
                GAS_95: provinceData.GAS_95,
                GAS_95_STATUS: provinceData.GAS_95_STATUS,
              },
              {
                text: "98",
                name: "汽油",
                price: provinceData.GAS_98,
                price_status: provinceData.GAS_98_STATUS,
                GAS_98: provinceData.GAS_98,
                GAS_98_STATUS: provinceData.GAS_98_STATUS,
              },
              {
                text: "0",
                name: "柴油",
                price: provinceData.CHECHAI_0,
                price_status: provinceData.CHECHAI_0_STATUS,
                CHECHAI_0: provinceData.CHECHAI_0,
                CHECHAI_0_STATUS: provinceData.CHECHAI_0_STATUS,
              }
            ];
            this.setData({
              arr: arr
            })
          }
          // 把arr数组存存储在本地
          let historys = this.data.historys;
          let datetime = util.formatTime2(new Date())
          let isHas = historys.some(item => {
            return item.datetime == datetime && item.provice == provice
          })
          if (!isHas) {
            let obj = {}
            obj.provice = provice
            obj.datetime = datetime;
            obj.result = arr
            historys.unshift(obj);
            let data = historys.slice(0, 50)
            wx.setStorageSync('YOUJIA_HISTORY', data)
          }
          wx.hideLoading()
        }
      )
      .catch(err => {
        console.log(err)
        wx.showToast({
          title: '请求失败',
          icon: 'error'
        })

        wx.hideLoading()
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 初始化
    this.searchOilPriceFn();
    this.historyDataFn();
    this.getCurrentDateTime();

    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-234ba9a4e19db710'
      })
      //
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {
        console.error('激励视频光告加载失败', err)
      })
      videoAd.onClose((res) => {
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励
          this.setData({
            isShow2: true
          })
        } else {
          // 播放中途退出，不下发游戏奖励
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 显示广告，观看完成可以领取资料的方法
  showVideoAdFn() {
    wx.showModal({
      title: '温馨提示',
      content: '完整观看视频广告，获取小程序源代码和制作教程',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          try {
            // 用户触发广告后，显示激励视频广告
            if (videoAd) {
              videoAd.show().catch(() => {
                // 失败重试
                videoAd.load()
                  .then(() => {
                    videoAd.show()
                  })
                  .catch(err => {
                    console.error('激励视频 广告显示失败', err)
                  })
              })
            }
          } catch (e) {
            console.log(e)
          }
        }
      }
    })
  },

  // 原生模板广告
  adLoad() {
    console.log('原生模板广告加载成功')
  },
  adError(err) {
    console.error('原生模板广告加载失败', err)
  },
  adClose() {
    console.log('原生模板广告关闭')
  },
  // 长按保存
  saveImage(e) {
    let that = this
    wx.showActionSheet({
      itemList: ['保存到相册'],
      success(res) {
        let url = e.currentTarget.dataset.url;
        wx.getSetting({
          success: (res) => {
            console.log(res);
            if (!res.authSetting['scope.writePhotosAlbum']) { // 未授权
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success: () => {
                  that.saveImgSuccess(url);
                },
                fail: (res) => {
                  console.log(res);
                  wx.showModal({
                    title: '保存失败',
                    content: '请开启访问手机相册的权限',
                    success(res) {
                      wx.openSetting()
                    }
                  })
                }
              })
            } else { // 已授权
              that.saveImgSuccess(url);
            }
          },
          fail: (res) => {
            console.log(res);
          }
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  // 同意授权保存到相册
  saveImgSuccess(url) {
    wx.getImageInfo({
      src: url, // 通过getImageInfo将src转换成改图片的本地路径，给saveImageToPhotosAlbum使用
      success: (res) => {
        console.log(res)
        let path = res.path;
        wx.saveImageToPhotosAlbum({
          filePath: path, // filePath路径不能是网络图片路径
          success: (res) => {
            console.log(res);
            wx.showToast({
              title: '已保存到相册',
            })
          },
          fail: (res) => {
            console.log(res);
          }
        })
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  // 查看大图
  imgClick() {
    var imgUrl = this.data.imgSrc;
    console.log('imgClick success', imgUrl)
    wx.previewImage({
      current: imgUrl, //当前显示图片的链接
      urls: [imgUrl], //需要预览的图片链接列表
      success: (res => {
        console.log('接口调用成功', res)
      })
    })
  },
  // 点击复制
  copyAction() {
    wx.setClipboardData({
      data: this.data.copyText || e.currentTarget.dataset.copytext, //这是复制的内容
      success(res) {
        wx.getClipboardData({
          success(res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
})